import {createRouter, createWebHistory, Router, RouteRecordRaw} from 'vue-router';
import {markRaw} from 'vue';
import Layout from '@/layout/Layout.vue';
import {useAuthStore} from '@/stores/auth';
import type { Component } from 'vue';

const RawLayout = markRaw(Layout) // 标记为原始对象

const modules = import.meta.glob('@/views/**/**.vue');

const STATIC_ROUTES: Array<RouteRecordRaw> = [
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: () => import('@/views/dashboard/index.vue'),
                meta: {
                    title: '仪表盘',
                    requiresAuth: true,
                },
            },
            {
                path: 'my',
                name: 'My',
                component: () => import('@/views/dashboard/my.vue'),
                meta: {
                    title: '个人信息',
                    requiresAuth: true,
                },
            },
        ],
    },
    {
        path: '/login',
        component: () => import('@/views/login/login.vue'),
        name: 'Login',
    },
];

// 创建路由实例
const router: Router = createRouter({
    history: createWebHistory(),
    routes: STATIC_ROUTES,
});

interface DynamicRoute {
    path: string;
    name?: string;
    component?: string | Component | (() => Promise<any>);
    redirect?: string;
    meta?: Record<string, unknown>;
    children?: DynamicRoute[];
}

// 动态加载路由
export function mountDynamicRoutes() {
    const authStore = useAuthStore();
    const dynamicRoutes = authStore.routes;
    console.log(dynamicRoutes ,'dynamicRoutes');
    // 移除旧的动态路由
    dynamicRoutes.forEach(route => {
        if (router.hasRoute(route.name!)) {
            router.removeRoute(route.name!);
        }
    });

    // 定义一个递归函数来处理路由和子路由
    const processRoute = (route: DynamicRoute, isChild: boolean = false) => {
        // 处理当前路由组件
        if (route.component && typeof route.component === 'string') {
            const comp = modules[`/src/views/${route.component}.vue`];
            if (comp) route.component = comp;
            else console.warn(`组件 ${route.component} 未找到`);

        } else if (!isChild && (!route.component || typeof route.component !== 'function')) { // 仅当不是子路由且没有有效组件时使用默认布局
            route.component = RawLayout;
        }

        // 递归处理子路由（标记为子级）
        if (route.children && Array.isArray(route.children)) {
            route.children.forEach(childRoute => {
                processRoute(childRoute, true); // 标记为子路由
            });
        }
    };

    // 遍历dynamicRoutes数组，调用processRoute函数
    dynamicRoutes.forEach(route => processRoute(route));

    // 添加动态路由
    dynamicRoutes.forEach(route => {
        if (!router.hasRoute(route.name!)) {
            router.addRoute(route);
        }
    });

    // 确保404页面始终可用
    router.addRoute({ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('@/views/error/404.vue') });
}

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore();

    // 设置浏览器标签标题
    const defaultTitle = authStore.system?.site_title || ''; // 默认标题
    document.title = to.meta.title ? `${String(to.meta.title)} - ${defaultTitle}` : defaultTitle;

    // 检查是否需要登录
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!authStore.isAuthenticated) {
            next({ path: '/login', query: { redirect: to.fullPath } }); // 跳转到登录页，并保存目标地址
            return;
        }
    }

    // 已登录情况下不允许访问登录页面
    if (to.path === '/login' && authStore.isAuthenticated) {
        next({ path: '/' }); // 重定向到主页或仪表盘
        return;
    }

    // 检查动态路由是否已加载
    if (authStore.isAuthenticated && !authStore.isDynamicRoutesLoaded) {
        mountDynamicRoutes();
        authStore.setDynamicRoutesLoaded(true);
        next({ ...to, replace: true }); // 重新导航到原目标地址
        return;
    }

    // 正常情况继续导航
    next();
});

export default router;